package com.feishi.core.util.serialize.fst;



import org.nustaq.serialization.FSTConfiguration;
import org.nustaq.serialization.FSTObjectInput;
import org.nustaq.serialization.FSTObjectOutput;

import java.io.*;

/**
 * Created by caixq on 4/27 027.
 */
public class SerializeFstUtil {
    static FSTConfiguration conf = FSTConfiguration.createDefaultConfiguration();


    public static <T> T readObject(byte[] bytes,Class<T> T) throws Exception {
        return readObject(new ByteArrayInputStream(bytes),T);
    }
    public static <T> T readObject(InputStream in,Class<T> t) throws Exception {
        FSTObjectInput input = conf.getObjectInput(in);
        T readObject = (T) input.readObject(t);
        return readObject;
    }

    public static <T> void writeObject(OutputStream stream, T t ) throws IOException{
        FSTObjectOutput out = conf.getObjectOutput(stream);
        out.writeObject( t, t.getClass());
        // DON'T out.close() when using factory method;
        out.flush();
    }
    public static <T> byte[] getBytes(T t ) throws IOException{
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        FSTObjectOutput output = conf.getObjectOutput(out);
        output.writeObject( t, t.getClass());
        // DON'T out.close() when using factory method;
        output.flush();
        byte[] arr = out.toByteArray();
        out.close();
        return arr;
    }

}
